# 代码块结构修复脚本 - 确保每个冒号后都有正确的缩进块
import os
import re

# 文件路径
original_file = r'd:\未知\yolo_apply\video_processing\video_processor.py'
final_backup = r'd:\未知\yolo_apply\video_processing\video_processor.py.final_backup'
temp_file = r'd:\未知\yolo_apply\video_processing\block_fixed.py'

# 确保我们使用最终备份
if os.path.exists(final_backup):
    print(f"Using backup to fix block structure: {final_backup}")
    
    # 尝试不同的编码方式读取文件
    encoding = 'utf-8'
    try:
        with open(final_backup, 'r', encoding=encoding) as f:
            content = f.read()
    except UnicodeDecodeError:
        encoding = 'latin-1'
        with open(final_backup, 'r', encoding=encoding) as f:
            content = f.read()
    
    # 规范化换行符
    content = content.replace('\r\n', '\n')
    content = content.replace('\r', '\n')
    
    # 按行分割
    lines = content.split('\n')
    
    # 修复代码块结构
    new_lines = []
    indent_stack = []  # 跟踪缩进级别的堆栈
    
    for i, line in enumerate(lines):
        stripped = line.strip()
        current_indent = len(line) - len(stripped)
        
        # 跳过空行和纯注释
        if not stripped or stripped.startswith('#'):
            new_lines.append(line)
            continue
        
        # 检查是否是代码块开始（以冒号结尾）
        if stripped.endswith(':'):
            # 确保有正确的缩进
            if indent_stack and current_indent <= indent_stack[-1]:
                # 如果当前行缩进小于等于堆栈最后一个元素，需要弹出堆栈直到找到合适的缩进级别
                while indent_stack and current_indent <= indent_stack[-1]:
                    indent_stack.pop()
            
            # 添加这行到新内容
            new_lines.append(line)
            
            # 将下一级缩进推入堆栈
            next_indent = current_indent + 4  # Python标准4空格缩进
            indent_stack.append(next_indent)
            
            # 检查下一行是否是该缩进级别的代码，如果没有则需要添加一个空的缩进块
            if i + 1 < len(lines):
                next_line_stripped = lines[i+1].strip()
                next_line_indent = len(lines[i+1]) - len(next_line_stripped)
                if next_line_indent < next_indent:
                    # 下一行缩进不够，需要添加一个pass语句
                    new_lines.append(' ' * next_indent + 'pass')
        else:
            # 不是代码块开始，检查缩进是否正确
            if indent_stack and current_indent < indent_stack[-1]:
                # 如果当前行缩进小于堆栈最后一个元素，需要弹出堆栈直到找到合适的缩进级别
                while indent_stack and current_indent < indent_stack[-1]:
                    indent_stack.pop()
            
            # 添加这行到新内容
            new_lines.append(line)
    
    # 将新行列表重新组合为文本
    new_content = '\n'.join(new_lines)
    
    # 写入修复后的文件
    with open(temp_file, 'w', encoding=encoding) as f:
        f.write(new_content)
    
    print(f"Created block structure fixed file: {temp_file}")
    
    # 替换原文件
    os.replace(temp_file, original_file)
    print(f"Replaced original file with block structure fixed version")
    print("Now let's try to compile again...")
else:
    print(f"Error: Final backup file not found: {final_backup}")